//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client.creation;

import java.util.Arrays;

import com.google.gwt.user.client.ui.HTML;

public abstract class Checker {
	private static final String LETTER[] = { "あかさたなはまやらわいきしちにひみりをうくすつぬふむゆるんえけせてねへめれおこそとのほもよろーがぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺぽぁぃぅぇぉゃゅょっ", "アカサタナハマヤラワイキシチニヒミリヲウクスツヌフムユルンエケセテネヘメレオコソトノホモヨローガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポァィゥェォャュョッヴ", "１２３４５６７８９０ＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＶＷＸＹＺ" };

	private static final String HALF_FULL_LETTER[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "ＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＶＷＸＹＺ０１２３４５６７８９" };

	private final PanelProblemCreation panelProblemCreation;

	protected Checker(PanelProblemCreation panelProblemCreation) {
		this.panelProblemCreation = panelProblemCreation;
	}

	protected boolean checkTypingAnswer(String answer) {
		if (answer == null || answer.length() == 0) {
			return false;
		}

		for (int letterType = 0; letterType < LETTER.length; ++letterType) {
			if (LETTER[letterType].indexOf(answer.charAt(0)) != -1) {
				for (int index = 0; index < answer.length(); ++index) {
					if (LETTER[letterType].indexOf(answer.charAt(index)) == -1) {
						return false;
					}
				}
				return true;
			}
		}

		return false;
	}

	protected String toFull(String answer) {
		for (int i = 0; i < HALF_FULL_LETTER[0].length(); ++i) {
			final String from = HALF_FULL_LETTER[0].substring(i, i + 1);
			if (answer.indexOf(from) != -1) {
				final String to = HALF_FULL_LETTER[1].substring(i, i + 1);
				answer = answer.replaceAll(from, to);
			}
		}

		return answer;
	}

	protected boolean check(WidgetProblemForm form) {
		boolean result = true;

		if (form.getListBoxGenre().getSelectedIndex() <= 0) {
			result = false;
			warn("ジャンルを選択してください");
		}

		if (form.getListBoxType().getSelectedIndex() <= 0) {
			result = false;
			warn("出題形式を選択してください");
		}

		if (form.getTextAreaSentence().getText().trim().length() == 0) {
			result = false;
			warn("問題文を入力してください");
		}

		if (form.getTextBoxCreater().getText().trim().length() == 0) {
			result = false;
			warn("作成者名を入力してください");
		}

		if (form.isImageAnswer()) {
			final int numberOfAnswer = form.getNumberOfAnswers();
			for (int i = 0; i < numberOfAnswer; ++i) {
				final String answer = form.getTextBoxAnswer(i);
				if (!isUrl(answer)) {
					result = false;
					warn((i + 1) + "個目の解答が画像URL形式になっていません");
				}
			}
		}

		if (form.isImageChoice()) {
			final int numberOfChoice = form.getNumberOfChoice();
			for (int i = 0; i < numberOfChoice; ++i) {
				final String choice = form.getTextBoxChoice(i);
				if (!isUrl(choice)) {
					result = false;
					warn((i + 1) + "個目の選択肢が画像URL形式になっていません");
				}
			}
		}

		if (form.getRandomFlag() == 5) {
			result = false;
			warn("下記を参考にランダムフラグを1～4の中から選んでください");
		}

		return result;
	}

	private static final String regex = "\\b(?:https?|shttp)://(?:(?:[-_.!~*'()a-zA-Z0-9;:&=+$,]|%[0-9A-Fa-f][0-9A-Fa-f])*@)?(?:(?:[a-zA-Z0-9](?:[-a-zA-Z0-9]*[a-zA-Z0-9])?\\.)*[a-zA-Z](?:[-a-zA-Z0-9]*[a-zA-Z0-9])?\\.?|[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+)(?::[0-9]*)?(?:/(?:[-_.!~*'()a-zA-Z0-9:@&=+$,]|%[0-9A-Fa-f][0-9A-Fa-f])*(?:;(?:[-_.!~*'()a-zA-Z0-9:@&=+$,]|%[0-9A-Fa-f][0-9A-Fa-f])*)*(?:/(?:[-_.!~*'()a-zA-Z0-9:@&=+$,]|%[0-9A-Fa-f][0-9A-Fa-f])*(?:;(?:[-_.!~*'()a-zA-Z0-9:@&=+$,]|%[0-9A-Fa-f][0-9A-Fa-f])*)*)*)?(?:\\?(?:[-_.!~*'()a-zA-Z0-9;/?:@&=+$,]|%[0-9A-Fa-f][0-9A-Fa-f])*)?(?:#(?:[-_.!~*'()a-zA-Z0-9;/?:@&=+$,]|%[0-9A-Fa-f][0-9A-Fa-f])*)?";

	protected boolean isUrl(String url) {
		if (!url.matches(regex)) {
			return false;
		}

		return true;
	}

	protected void warn(String text) {
		final HTML html = new HTML(text);
		html.addStyleDependentName("problemCreationWarning");
		panelProblemCreation.getPanelWarning().add(html);
	}

	protected int[] toArray(String s) {
		final int length = s.length();
		final int[] result = new int[length];
		for (int i = 0; i < length; ++i) {
			result[i] = s.charAt(i);
		}
		Arrays.sort(result);
		return result;
	}
}
